package isssr.bean.utility;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

import org.hibernate.Query;

import org.hibernate.Session;

public class QueryBuilder {

	private class QueryString{

		private int parameters;
		private String query;
	
		public QueryString(Class classtype)
		{
			parameters = 0;
			query = "select " + classtype.getSimpleName() + " as o";
		}

		public void addParameterSet(Set<Entry<String,Object>> parameters)
		{
			for(Entry<String, Object> parameter : parameters )
			{
				addParameter(parameter.getKey(), parameter.getValue());
			}
		}
		public void addParameter(String name, Object object)
		{
			
			String fragment = parseParameter(name, object);
			
			if(fragment == null || fragment == "")
				return;
			
			String result;
			
			if(parameters==0)
				result = " where " + fragment;			
			else
				result = " and " + fragment;			
			
			parameters +=1;
			
			this.query.concat(result);
		}

		private String parseParameter(String name, Object object)
		{
			if(object instanceof Collection)
				return parseCollectionParameter(name, (Collection)object);
			else
				return parseBaseTypeFragment(name, object);
		}
		
		private String parseCollectionParameter(String name, Collection collection)
		{
			String queryFragment = "";
			
			if(collection != null && !collection.isEmpty())
			{
				queryFragment = "o." + name + " in (:" + name +")";
			}
			else
			{
				return null;
			}
			
			return queryFragment;
		}
		
		private String parseBaseTypeFragment(String name, Object object)
		{
			String queryFragment = "";
			
			if(object != null)
			{
				queryFragment = "o." + name + " = :" + name +")";
			}
			else
			{
				return null;
			}
			
			return queryFragment;
		}
		
	}
	
	private Session currentSession;
	private QueryString queryString;
	
	public QueryBuilder(Class classtype)
	{
		currentSession = currentSession;
		queryString = new QueryString(classtype);
	}
	
	
	public Query buildQuery(Set<Entry<String,Object>> parameters, Session session)
	{
		this.queryString.addParameterSet(parameters);
		
		return null;
	}
}
